/* eslint-disable strict */
/* eslint-disable object-shorthand */
/* eslint-disable no-alert */

// 去除空格
$('input[type=text]').on('keyup', function() {
  this.value = this.value.trim();
});
// 处理url信息
let htmlHref = location.href;
htmlHref = htmlHref.replace(/^http:\/\/[^/]+/, '');
const addr = htmlHref.substr(htmlHref.lastIndexOf('/', htmlHref.lastIndexOf('/') - 1) + 1);
const index = addr.lastIndexOf('\/');
const id = decodeURI(addr.substring(index + 1, addr.length));
// 保存用户名至localStorage
const username = localStorage.getItem('username');
if (username) {
  $('#name').val(username);
} else {
  $('#name').val('');
}

// TODO 逻辑重写——恶心的class语法
class PostComment {
  constructor({ name, face, content, user_id }) {
    this.name = name.replace(/做爱|黄色|日|妈|操|gay|fuck/gi, '**');
    this.face = face;
    this.content = content.replace(/做爱|黄色|日|妈|操|gay|fuck/gi, '**');
    this.user_id = user_id;
    this.time = new Date().toLocaleString();
  }
  validateData() {
    if (!this.content.replace(/ +/g, '').replace(/[\r\n]/g, '')) {
      alert('请输入内容！');
      return false;
    }
    return true;
  }
  updateCount() {
    let oldCount = +($('#comment_count > span').text());
    $('#comment_count > span').text(++oldCount);
  }
  comment() {
    if (!this.validateData()) {
      return false;
    }
    const that = this;
    $.ajax({
      type: 'POST',
      url: `/article/${id}`,
      data: {
        name: this.name,
        content: this.content,
        time: this.time,
        face: this.face,
      },
      success(data) {
        if (data.success) {
          $('.emoji_box').hide();
          localStorage.setItem('username', data.message.name);
          that.updateCount();
          // 成功通知
          $('.toast').toast('show');
          const content = `
           <tr>
              <td>
                <div class="touxiang">
                    <img
                      src=${data.message.face}
                      alt="人物头像"
                      width="50"
                      height="50"
                    />
                    <div>${data.message.name}</div>
                 </div>
                 <div class="content">
                    ${data.message.content}
                    <br />
                    <small>${data.message.time}</small>
                 </div>
              </td>
           </tr>`;
          $('.table tbody').prepend(content);
          $('#form')[0].reset();
        } else {
          alert('非法错误！');
          return false;
        }
      },
      error() {
        alert('请输入正确的格式！');
      },
    });
  }
  reply(reply_name, user_id) {
    if (!this.validateData()) {
      return false;
    }
    const that = this;
    const url = `/reply?id=${this.user_id}&blog_id=${id}`;
    const data = {
      name: this.name,
      content: this.content,
      time: this.time,
      face: this.face,
      reply_name: reply_name,
    };
    $.ajax({
      type: 'POST',
      url,
      data,
      success(data) {
        if (data.success) {
          that.updateCount();
          $(`#${that.user_id}`).parent().append(`
            <div class="hf">
              <div class="reply_area">
                <span class="reply_info">
                  <img
                    src=${data.message.reply_face}
                    alt="人物头像"
                    width="50"
                    height="50"
                  />
                  <span>${data.message.name}
                    <span class="text-info">&nbsp;回复&nbsp;</span>
                    <span>${data.message.reply_name}</span>：
                  </span>
                  <span class="reply_content">
                    ${data.message.reply_comment}<br />
                    <small>${data.message.reply_time}</small>
                  </span>
                </span>
              </div>
            </div>
          `);
          $('.toast').toast('show');
          $(`#${user_id}`)[0].reset();
          $(`#${user_id}`).hide();
        } else {
          alert('非法错误！');
          return false;
        }
      },
      error() {
        alert('请输入正确的格式！');
      },
    });
  }
}
// 提交评论
$('#form').on('submit', function(e) {
  const name = $('input[name=name]').val(),
    content = $('#form-control').val(),
    face = $('select[name=face]').val();
  new PostComment({ name, content, face }).comment();
  e.preventDefault();
  return false;
});

function reply(user_id, comment_id, reply_name) {
  let flag = true;
  // 隐藏原评论框
  $('#form').css('display', 'none');
  $('.table form').css('display', 'none');
  // 显示回复评论框
  $(`#${user_id}`).show();
  // 提交回复
  $(`#${user_id}`).on('submit', function(e) {
    if (flag) {
      const name = $(`#${user_id} input[type=text]`).val(),
        content = $(`#${user_id} .form-control`).val(),
        face = $(`#${user_id} select[name=face]`).val();
      new PostComment({ user_id: comment_id, name, face, content }).reply(reply_name, user_id);
      flag = false;
      e.preventDefault();
      return false;
    }
  });
}

